<?php
declare(strict_types=1);

namespace Service\UserService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\OpenIdInfo;
use App\Model\BbcModel\OpenId;

/**
 * 微信数据绑定服务中心
 * @author chenshubo
 */
class WxBindLoginService extends BaseService
{
    /**
     * 开始绑定数据
     * @param string $client
     * @param int $cid
     * @param int $mnid
     * @param int $mn_sid
     * @param int $mid
     * @param array $param
     * @return mixed
     */
    public function bind(string $client,int $cid,int $mnid,int $mn_sid,int $mid,array $param)
    {
        //是否绑定
        $where_bind  = [
            'tob'           => $client,
            'mid'           => $mid,
            'mnid'          => $mnid,
            'cid'           => $cid,
            'mn_sid'        => $mn_sid
        ];
        $bind = OpenId::instance()->info($where_bind);
        
        //是否绑定更新数据
        $is_bind_add = false;
        if ( !empty($bind) ) 
        {
            $bind['token']       = !empty($param['token']) ? $param['token'] : '';
            $bind['openid']      = !empty($param['openid']) ? $param['openid'] : '';
            $bind['expir_time']  = !empty($param['expir_time']) ? $param['expir_time'] : 0;
            $bind['unionid']     = !empty($param['unionid']) ? $param['unionid'] : '';
            $bind['mnid']        = $mnid;
            $bind['md']          = time();
            $result_bind = OpenId::instance()->where('id',$bind['id'])->update($bind);
        }
        else 
        {
            $bind = [
                'tob'        => $client,
                'mid'        => $mid,
                'mnid'       => $mnid,
                'cid'        => $cid,
                'mn_sid'     => $mn_sid,
                'token'      => !empty($param['token']) ? $param['token'] : '',
                'openid'     => !empty($param['openid']) ? $param['openid'] : '',
                'unionid'    => !empty($param['unionid']) ? $param['unionid'] : '',
                'expir_time' => !empty($param['expir_time']) ? $param['expir_time'] : 0,
                'cd'         => time(),
            ];
            $result_bind = OpenId::instance()->add($bind);
            $is_bind_add = true;
        }
        
        if( !$result_bind ) {
            return Normal::returnCode(Normal::FAIL,"绑定写入失败，请稍后再试!");
        }
        
        //写入详情
        if ( $is_bind_add ) {
            OpenIdInfo::instance()->add([
                'id'    => $result_bind
            ]);
            $bind['id'] = $result_bind;
        }
        
        return Normal::returnCode(Normal::SUC,"绑定成功",$bind);
    }
}